package es.agroservicio.Agroservicio.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import es.agroservicio.Agroservicio.domain.Client;

@Repository
@Transactional
public class ClientsDAOImpl implements ClientsDAO {

	private EntityManager em;

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	public Client findById(String id) {
		return em.find(Client.class, id);
	}

	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public List<Client> findAllOrderedByName() {
		return em.createQuery("select c from Client c order by c.name")
				.getResultList();
	}

	public void register(Client client) {
		em.persist(client);
		return;

	}

	public void saveOrUpdate(Client client) {
		em.merge(client);

	}

	public void deleteClient(Client client) {

		Client c = em.find(Client.class, client.getDni());
		if (c != null)
			em.remove(c);

	}

}
